package com.zang.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * entity转换工具类
 */
public class EntityUtils {
	private static final Logger log = LogManager.getLogger(EntityUtils.class);
	/**
	 * 实体类转Map
	 * @param object 对象
	 * @return map
	 */
	public static Map<String, Object> entityToMap(Object object) {
		Map<String, Object> map = new HashMap<>();
	    for (Field field : object.getClass().getDeclaredFields()){
	        try {
	        	boolean flag = field.isAccessible();
	            field.setAccessible(true);
	            Object o = field.get(object);
	            map.put(field.getName(), o);
	            field.setAccessible(flag);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    return map;
	}

	public static JSONObject beanToJSON(Object obj) {
		JSONObject jsonObject = new JSONObject();
		try {
			Field[] declaredFields = obj.getClass().getDeclaredFields();
			for (Field field : declaredFields) {
				field.setAccessible(true);
				Object o = field.get(obj) == null ? "" : field.get(obj);
				jsonObject.put(field.getName(), o);
			}
		} catch (Exception e) {
			log.error("【{}】", e.getMessage());
			e.printStackTrace();
		}

		return jsonObject;
	}

	/**
	 * 实体类转Map
	 * @param object 对象
	 * @return map
	 */
	public static Map<String, String> entityToStringMap(Object object) {
		Map<String, String> map;
		String json = JSON.toJSONString(object);
		map = JSON.parseObject(json, new TypeReference<Map<String, String>>(){});
		return map;
	}

	/**
	 * Map转实体类
	 * @param map 需要初始化的数据，key字段必须与实体类的成员名字一样，否则赋值为空
	 * @param clazz  需要转化成的实体类类型
	 * @return 对象
	 */
	public static <T> T stringMapToEntity(Map<String, String> map, Class<T> clazz) {
		if(map == null)
			return null;
		if(clazz == null)
			return null;
		if(map.size() == 0)
			return null;
		String json = JSON.toJSONString(map);
		JSONObject jsonObject = JSONObject.parseObject(json);
		return JSON.toJavaObject(jsonObject, clazz);
	}
	
	/**
	 * Map转实体类
	 * @param map 需要初始化的数据，key字段必须与实体类的成员名字一样，否则赋值为空
	 * @param clazz  需要转化成的实体类类型
	 * @return 对象
	 */
	public static <T> T mapToEntity(Map<String, Object> map, Class<T> clazz) {
		T t = null;
		try {
			t = clazz.newInstance();
			for(Field field : clazz.getDeclaredFields()) {
				if (map.containsKey(field.getName())) {
					boolean flag = field.isAccessible();
		            field.setAccessible(true);
		            Object object = map.get(field.getName());
		            if (object!= null && field.getType().isAssignableFrom(object.getClass())) {
		            	 field.set(t, object);
					}
		            field.setAccessible(flag);
				}
			}
			return t;
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return t;
	}
}